package com.vegetable.modules.service.finance.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vegetable.common.constant.CommonConstant;
import com.vegetable.common.utils.Constant;
import com.vegetable.common.utils.PageUtils;
import com.vegetable.common.utils.Query;
import com.vegetable.common.utils.R;
import com.vegetable.modules.entity.finance.FinancialOther;
import com.vegetable.modules.entity.finance.po.FinancialDoneDetailPO;
import com.vegetable.modules.entity.finance.po.FinancialDoneMainPO;
import com.vegetable.modules.mapper.finance.FinancialOtherMapper;
import com.vegetable.modules.service.baseData.IFundAccountService;
import com.vegetable.modules.service.finance.IFinancialOtherService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 其他收款 服务实现类
 * </p>
 *
 * @author wangruijie
 * @since 2024-04-15
 */
@Slf4j
@Service
@AllArgsConstructor
public class FinancialOtherServiceImpl extends ServiceImpl<FinancialOtherMapper, FinancialOther> implements IFinancialOtherService {

    private IFundAccountService accountService;
    /**
     * 其他收款列表查询
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String docNo = (String)params.get("docNo");
        // 状态0未收，1已收完
        Object mode = params.get("mode");
        Object type = params.get("type");
        String startTime = (String)params.get("startTime");
        String endTime = (String)params.get("endTime");
        IPage<FinancialOther> page = this.page(
                new Query<FinancialOther>().getPage(params),
                new QueryWrapper<FinancialOther>()
                        .between(StringUtils.isNotBlank(startTime), "order_time", startTime, endTime)
                        .eq(ObjectUtils.isNotEmpty(mode),"mode", mode)
                        .eq(ObjectUtils.isNotEmpty(type),"type", type)
                        .eq(ObjectUtils.isNotEmpty(params.get("unitId")),"unit_id", params.get("unitId"))
                        .eq(ObjectUtils.isNotEmpty(params.get("subjectId")),"subject_id", params.get("subjectId"))
                        .eq(ObjectUtils.isNotEmpty(params.get("accountId")),"account_id", params.get("accountId"))
                        .like(StringUtils.isNotBlank(docNo),"doc_no", docNo)
                        .orderByDesc("create_time")
        );

        return new PageUtils(page);
    }

    /**
     * 查询可增补实录数据列表
     * @param
     * @return List<FinancialOther>
     * @author wrj
     * @since 2024/4/28 下午2:24
     */
    @Override
    public List<FinancialOther> canAddedList(Integer type) {
        // 0未收
        List<FinancialOther> list = this.list(
                new QueryWrapper<FinancialOther>()
                        // 收款
                        .eq("type", type)
                        .eq("mode", 0)
                        .orderByDesc("create_time")
        );
        return list;
    }

    /**
     * 新增其他收款
     * @param order null
     * @return R
     * @author wrj
     * @since 2024/3/7 下午4:35
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R saveOther(FinancialOther order) throws Exception {
        if (order.getId() == null){
            order.setDocNo(CommonConstant.QTSK+ baseMapper.getNextCode());
            order.setOrderTime(new Date());
            if (order.getMode() == 0){
                order.setUncalledMoney(order.getMoney());
            }else {
                // 更新总收款
//                FundAccount account_in = accountService.getById(order.getAccountId());
//                if (account_in != null){
//                    BigDecimal totalReceipts = account_in.getTotalReceipts();
//                    totalReceipts = totalReceipts.add(order.getMoney());
//                    account_in.setTotalReceipts(totalReceipts);
//                    accountService.updateById(account_in);
//                }
                accountService.addReceipts(order.getAccountId(), order.getMoney(), Constant.MoneyTYPE.OTHER_IN, order.getDocNo(), order.getId(), order.getUnitName());
            }
        }
        this.saveOrUpdate(order);
        return R.status(true);
    }

    /**
     * 增补实录确定
     * @param po null
     * @return R
     * @author wrj
     * @since 2024/4/28 下午2:30
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R done(FinancialDoneMainPO po) {
        for (FinancialDoneDetailPO detailPO:po.getItems()) {
            FinancialOther other = baseMapper.selectById(detailPO.getId());
            if (other != null){
                other.setAccountId(po.getAccountId());
                other.setAccountName(po.getAccountName());
                if (other.getUncalledMoney().compareTo(detailPO.getMoney()) ==0 ){
                    // 状态0未收，1已收完"
                    other.setMode(1);
                    other.setUncalledMoney(BigDecimal.ZERO);

                }else {
                    // 状态0未收，1已收完"
                    other.setMode(0);
                    BigDecimal subtract = other.getUncalledMoney().subtract(detailPO.getMoney());
                    other.setUncalledMoney(subtract);
                }
                // 状态0收款，1付款
                if (other.getType() == 0){
                    // 更新总收款
//                    FundAccount account_in = accountService.getById(other.getAccountId());
//                    if (account_in != null){
//                        BigDecimal totalReceipts = account_in.getTotalReceipts();
//                        totalReceipts = totalReceipts.add(detailPO.getMoney());
//                        account_in.setTotalReceipts(totalReceipts);
//                        accountService.updateById(account_in);
//                    }
                    accountService.addReceipts(other.getAccountId(), detailPO.getMoney(), Constant.MoneyTYPE.OTHER_IN, other.getDocNo(), other.getId(), null);

                }else {
                    // 更新总支出
//                    FundAccount account_out = accountService.getById(other.getAccountId());
//                    if (account_out != null){
//                        BigDecimal totalExpenditure = account_out.getTotalExpenditure();
//                        totalExpenditure = totalExpenditure.add(detailPO.getMoney());
//                        account_out.setTotalExpenditure(totalExpenditure);
//                        accountService.updateById(account_out);
//                    }
                    accountService.addReceipts(other.getAccountId(), detailPO.getMoney(), Constant.MoneyTYPE.OTHER_OUT, other.getDocNo(), other.getId(), null);

                }

                baseMapper.updateById(other);
            }
        }
        return R.status(true);
    }

    /**
     * 新增其他付款
     * @param order null
     * @return R
     * @author wrj
     * @since 2024/3/7 下午4:35
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R saveOtherPayment(FinancialOther order) throws Exception {
        if (order.getId() == null){
            order.setDocNo(CommonConstant.QTFK+ baseMapper.getNextCode());
            order.setOrderTime(new Date());
        }
        // 更新总支出
//        FundAccount account_out = accountService.getById(order.getAccountId());
//        if (account_out != null){
//            BigDecimal totalExpenditure = account_out.getTotalExpenditure();
//            totalExpenditure = totalExpenditure.add(order.getMoney());
//            account_out.setTotalExpenditure(totalExpenditure);
//            accountService.updateById(account_out);
//        }

        this.saveOrUpdate(order);
        accountService.addReceipts(order.getAccountId(), order.getMoney(), Constant.MoneyTYPE.OTHER_OUT, order.getDocNo(), order.getId(), order.getUnitName());
        return R.status(true);
    }


    /**
     * 删除其他收款
     * @param id null
     * @return R
     * @author wrj
     * @since 2024/3/7 下午4:35
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R deleteOther(Long id) throws Exception {
//        FinancialOther selectById = baseMapper.selectById(id);
//        if (selectById == null){
//            throw new Exception("收款不存在");
//        }
//        // 状态0收款，1付款
//        if (selectById.getType() == 0){
//            // 更新总收款 回退
//            FundAccount account_in = accountService.getById(selectById.getAccountId());
//            if (account_in != null){
//                BigDecimal totalReceipts = account_in.getTotalReceipts();
//                totalReceipts = totalReceipts.subtract(selectById.getMoney());
//                account_in.setTotalReceipts(totalReceipts);
//                accountService.updateById(account_in);
//            }
//        }else {
//            // 更新总支出 回退
//            FundAccount account_out = accountService.getById(selectById.getAccountId());
//            if (account_out != null){
//                BigDecimal totalExpenditure = account_out.getTotalExpenditure();
//                totalExpenditure = totalExpenditure.subtract(selectById.getMoney());
//                account_out.setTotalExpenditure(totalExpenditure);
//                accountService.updateById(account_out);
//            }
//        }
//
//        baseMapper.deleteById(id);
        return R.status(true);
    }
}
